package com.example.demo.controller;

import com.example.demo.common.*;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.Remark;
import com.example.demo.entity.Videoinfo;
import com.example.demo.entity.vo.UserinfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.util.UUID;

import static com.example.demo.common.AppVariable.USER_SESSION_KEY;

@RestController
@RequestMapping("/user")
public class UserController implements Serializable {
    @Resource
    private UserService userService;
    @Resource
    private ArticleService articleService;
    @Autowired
    private CheckCodeTools codeTools;

    //注册
    @RequestMapping("/reg")
    public AjaxResult reg(Userinfo userinfo){
        //非空校验
        if(userinfo==null|| !StringUtils.hasLength(userinfo.getUsername())||!StringUtils.hasLength(userinfo.getPassword())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //密码加盐处理
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        //将data数据返回进行封装
        return AjaxResult.success(userService.reg(userinfo));
    }

    //登录
    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request, String username, String password,String code){
        //非空校验
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)
                ||!StringUtils.hasLength(code)){
            return AjaxResult.fail(-1,"非法请求");
        }
        //查询数据
        Userinfo userinfo=userService.getUserByName(username);
        if(userinfo!=null&&userinfo.getId()>0){
            //登录成功，数据正确
            if(PasswordUtils.check(password,userinfo.getPassword())){
                //将用户存储到session中去
                HttpSession session=request.getSession();
                session.setAttribute(USER_SESSION_KEY,userinfo);
                //返回之前隐藏密码，防止传输途中被截取
                userinfo.setPassword("");
                //从session中拿出验证码
                String getcode= (String) session.getAttribute(AppVariable.SESSION_KEY_CHECK_CODE);
                System.out.println(getcode);
                System.out.println(code);
                if(getcode.equals(code)) {
                    return AjaxResult.success(userinfo);
                }else{
                    return AjaxResult.fail(-1,"验证码有误");
                }
            }
        }
            //不在数据库中的数据
            return AjaxResult.success(0,null);
    }

    //返回用户信息
    @RequestMapping("/showinfo")
    public AjaxResult showinfo(HttpServletRequest request){
        UserinfoVO userinfoVO=new UserinfoVO();
        //1、获取当前登录用户(从session中获取)
        Userinfo userinfo= UserSessionUtils.getUser(request);
        if(userinfo==null){
            return AjaxResult.fail(-1,"非法请求！");
        }
        //spring提供的深克隆方法
        BeanUtils.copyProperties(userinfo,userinfoVO);
        //2、得到用户发表的文章
        userinfoVO.setArtCount(articleService.getArtCountByid(userinfo.getId()));
        return AjaxResult.success(userinfoVO);
    }

    //注销操作
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session){
        session.removeAttribute(USER_SESSION_KEY);
        return AjaxResult.success(1);
    }

    //文章详情页中返回的用户信息
    @RequestMapping("/getuserbyid")
    public AjaxResult getUserById(Integer id){
        if(id==null||id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo userinfo= userService.getUserById(id);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        UserinfoVO userinfoVO=new UserinfoVO();
        //去除敏感数据
        userinfo.setPassword("");
        BeanUtils.copyProperties(userinfo,userinfoVO);
        //设置文章数量
        userinfoVO.setArtCount(articleService.getArtCountByid(id));
        return AjaxResult.success(userinfoVO);
    }

    //返回用户草稿信息
    @RequestMapping("/showinfosave")
    public AjaxResult showinfosave(HttpServletRequest request){
        UserinfoVO userinfoVO=new UserinfoVO();
        //1、获取当前登录用户(从session中获取)
        Userinfo userinfo= UserSessionUtils.getUser(request);
        if(userinfo==null){
            return AjaxResult.fail(-1,"非法请求！");
        }
        //spring提供的深克隆方法
        BeanUtils.copyProperties(userinfo,userinfoVO);
        //2、得到用户发表的文章
        userinfoVO.setArtCount(articleService.getArtSaveCountByid(userinfo.getId()));
        return AjaxResult.success(userinfoVO);
    }

    //修改个人信息
    @RequestMapping("/regupdate")
    public AjaxResult regUpdate(HttpServletRequest request,String password0,String password){
        //非空校验
        if(password==null||!StringUtils.hasLength(password)||
                password0==null||!StringUtils.hasLength(password0)){
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"用户未登录");
        }
        if(password0.equals(password)){
            return AjaxResult.fail(-1,"修改密码和原密码不能一致");
        }
        userinfo=userService.getUserById(userinfo.getId());
        //判断原密码与数据库中密码是否相同
        if(!PasswordUtils.check(password0,userinfo.getPassword())){
            return AjaxResult.fail(-1,"原密码输入错误");
        }
        //密码加盐处理
        userinfo.setPassword(PasswordUtils.encrypt(password));
        //将data数据返回进行封装
        return AjaxResult.success(userService.regupdate(userinfo));
    }

    //返回所有人的评论
    @RequestMapping("/remarkall")
    public AjaxResult getRemarkAll(Integer id){
        if(id<=0){
            return AjaxResult.fail(-1,"参数异常");
        }
        return AjaxResult.success(userService.getRemarkAll(id));
    }
    //添加评论
    @RequestMapping("/remarkadd")
    public AjaxResult remarkAdd(HttpServletRequest request,Remark remark){
        if(remark==null||!StringUtils.hasLength(remark.getContent())){
            return AjaxResult.fail(-1,"参数有误");
        }
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"用户未登录");
        }
        remark.setUsername(userinfo.getUsername());
        userService.remarkadd(remark);
        return AjaxResult.success(1);
    }

    //进行验证码的生成和写回前端
    @RequestMapping("/getcode")
    public AjaxResult getCode(HttpServletRequest request) {
        String[] codeArr = codeTools.createImage();
        // 将验证码存储到 session
        HttpSession session = request.getSession();
        session.setAttribute(AppVariable.SESSION_KEY_CHECK_CODE, codeArr[1]);
        System.out.println(codeArr[1]);
        return AjaxResult.success("/image/" + codeArr[0]);
    }

    //进行个人设置页面的图片储存
    @RequestMapping("/upload")
    public AjaxResult handleFileUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                String fileName = UUID.randomUUID()+file.getOriginalFilename();
                String fileurl="E:/project/mycnblog/src/main/resources/static/img/";
                // 获取文件输入流
                InputStream inputStream = file.getInputStream();
                // 构造输出流，将文件保存到服务器上的指定目录中
                FileOutputStream out = new FileOutputStream(new File(fileurl+ fileName));
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
                // 关闭输入输出流
                out.close();
                inputStream.close();
                //对登陆用户进行session的获取
                Userinfo userinfo=UserSessionUtils.getUser(request);
                if(userinfo==null||userinfo.getId()<=0){
                    return AjaxResult.fail(-1,"用户未登录");
                }
                //构造图片信息对象
                Videoinfo videoinfo=new Videoinfo();
                videoinfo.setTitle(fileName);
                videoinfo.setUrl(fileurl);
                videoinfo.setUid(userinfo.getId());
                userService.videoadd(videoinfo);
                return AjaxResult.success(200,1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.fail(-1,null);
    }

    //获取数据库中的用户图片相信
    @RequestMapping("/getimg")
    public AjaxResult getimg(HttpServletRequest request){
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"用户未登录");
        }
        Videoinfo videoinfo=userService.getimg(userinfo.getId());
        if(videoinfo==null||videoinfo.getUid()<=0){
            return AjaxResult.fail(-1,"用户未保存图片");
        }
        return AjaxResult.success(200,videoinfo.getTitle());
    }

    //文章详情页从url中的id获取对应作者的头像,传入的是文章id
    @RequestMapping("/getimgcontent")
    public AjaxResult getimgcontent(Integer id,HttpServletRequest request){
        if(id==null||id<=0){
            return AjaxResult.fail(-1,"参数异常");
        }
        Articleinfo articleinfo=articleService.getDetail(id);
        Userinfo userinfo= userService.getUserById(articleinfo.getUid());
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        Videoinfo videoinfo=userService.getimg(userinfo.getId());
        if(videoinfo==null||videoinfo.getUid()<=0){
            return AjaxResult.fail(-1,"用户未保存图片");
        }
        return AjaxResult.success(200,videoinfo.getTitle());
    }

}
